//
//  YCOrderDetailViewController.m
//  lianganyuchu
//
//  Created by iMac on 17/2/28.
//  Copyright © 2017年 杭州桑缇电子商务有限公司. All rights reserved.
//

#import "YCOrderDetailViewController.h"
#define YCOrderStatusCellIdentify @"YCOrderStatusTableViewCell"
#define YCOrderMealCellIdentify @"YCOrderMealTableViewCell"
#define YCOrderAddressCellIdentify @"YCOrderAddressTableViewCell"
#define YCOrderRemarkCellIdentify @"YCOrderRemarkTableViewCell"
#define YCOrderDetailCellIdentify @"YCOrderDetailTableViewCell"
#define ButtonTag 1000

@interface YCOrderDetailViewController ()
{
    UITableView *m_tableView;
    UIView *m_footerView;
    OrderTable *_orderTable;
    
    UIButton *m_button1;
    UIButton *m_button2;
    UIButton *m_button3;
    
    OrderTable *_orderPrint;
}
@end

@implementation YCOrderDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title=@"订单详情";
    self.navigationItem.leftBarButtonItem=[self tbarBackButton];
    [self.view setBackgroundColor:WHITE_COLOR];
    
    [self loadData];
    [self addMainView];
}

-(void)loadData
{
    OrderDetailRequest *request = [OrderDetailRequest new];
    [apiClient hideProgress];
    [apiClient disableAfterRequest];
    request.order_no=_orderId;
    [apiClient doOrderDetail:request success:^(ApiResponse *data, NSString *url) {
        OrderDetailResponse *response=[[OrderDetailResponse alloc]initWithCGResponse:data];
        _orderTable=response.data;
        [m_tableView reloadData];
        [self reloadFooter];
    }failure:^(ApiResponse *data, NSString *url){
    }];
}
-(void)reloadFooter
{
   // 0：不显示按钮 1：确认接单 2：打印订单和客户自取 3：打印订单，平台配送和自己配送 4：打印订单和取消配送 5：打印订单 6：打印订单，自己配送和重新发单 7：查看评价
    if (_orderTable.button_type.intValue==0) {
        [m_footerView setHidden:YES];
        
        [m_tableView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view).offset(0);
            make.right.equalTo(self.view).offset(0);
            make.top.equalTo(self.view).offset(0);
            make.bottom.equalTo(self.view).offset(0);
        }];
    }else {
        [m_tableView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view).offset(0);
            make.right.equalTo(self.view).offset(0);
            make.top.equalTo(self.view).offset(0);
            make.bottom.equalTo(self.view).offset(-60);
        }];
        
        [m_footerView setHidden:NO];
        
        [m_button1 removeTarget:nil action:nil forControlEvents:UIControlEventTouchUpInside];
        [m_button2 removeTarget:nil action:nil forControlEvents:UIControlEventTouchUpInside];
        [m_button3 removeTarget:nil action:nil forControlEvents:UIControlEventTouchUpInside];
        if (_orderTable.button_type.intValue==1) {
            [m_button3 setHidden:NO];
            [m_button3 setTitle:@"确认接单" forState:UIControlStateNormal];
            [m_button3 setBackgroundColor:MAIN_COLOR];
            m_button3.layer.borderWidth=CGFLOAT_MIN;
            [m_button3 addTarget:self action:@selector(buttonHandelClicked:) forControlEvents:UIControlEventTouchUpInside];
            m_button3.tag=ButtonTag+1;
        }
        if (_orderTable.button_type.intValue==2) {
            [m_button3 setHidden:NO];
            [m_button3 setTitle:@"客户自取" forState:UIControlStateNormal];
            [m_button3 setBackgroundColor:MAIN_COLOR];
            m_button3.layer.borderWidth=CGFLOAT_MIN;
            [m_button3 addTarget:self action:@selector(buttonHandelClicked:) forControlEvents:UIControlEventTouchUpInside];
            m_button3.tag=ButtonTag+5;
            
            [m_button2 setHidden:NO];
            [m_button2 setTitle:@"打印订单" forState:UIControlStateNormal];
            [m_button2 addTarget:self action:@selector(buttonPrintClicked:) forControlEvents:UIControlEventTouchUpInside];
            m_button2.tag=ButtonTag;
        }
        if (_orderTable.button_type.intValue==3) {
            [m_button3 setHidden:NO];
            [m_button3 setTitle:@"自己配送" forState:UIControlStateNormal];
            [m_button3 setTitleColor:WHITE_COLOR forState:UIControlStateNormal];
            [m_button3 setBackgroundColor:MAIN_COLOR];
            m_button3.layer.borderWidth=CGFLOAT_MIN;
            [m_button3 addTarget:self action:@selector(buttonHandelClicked:) forControlEvents:UIControlEventTouchUpInside];
            m_button3.tag=ButtonTag+4;
            
            [m_button2 setHidden:NO];
            [m_button2 setTitle:@"平台配送" forState:UIControlStateNormal];
            [m_button2 setTitleColor:WHITE_COLOR forState:UIControlStateNormal];
            [m_button2 addTarget:self action:@selector(buttonHandelClicked:) forControlEvents:UIControlEventTouchUpInside];
            m_button2.tag=ButtonTag+2;
            
            [m_button1 setHidden:NO];
            [m_button1 setTitle:@"打印订单" forState:UIControlStateNormal];
            [m_button1 setTitleColor:WHITE_COLOR forState:UIControlStateNormal];
            [m_button1 addTarget:self action:@selector(buttonPrintClicked:) forControlEvents:UIControlEventTouchUpInside];
            m_button1.tag=ButtonTag;
        }
        if (_orderTable.button_type.intValue==4) {
            [m_button3 setHidden:NO];
            [m_button3 setTitle:@"取消配送" forState:UIControlStateNormal];
            [m_button3 setTitleColor:MAIN_COLOR forState:UIControlStateNormal];
            [m_button3 setBackgroundColor:WHITE_COLOR];
            m_button3.layer.borderWidth=1.0f;
            m_button3.layer.borderColor=MAIN_COLOR.CGColor;
            [m_button3 addTarget:self action:@selector(buttonHandelClicked:) forControlEvents:UIControlEventTouchUpInside];
            m_button3.tag=ButtonTag+6;
            
            [m_button2 setHidden:NO];
            [m_button2 setTitle:@"打印订单" forState:UIControlStateNormal];
            [m_button2 addTarget:self action:@selector(buttonPrintClicked:) forControlEvents:UIControlEventTouchUpInside];
            m_button2.tag=ButtonTag;
            
            [m_button1 setHidden:YES];
        }
        if (_orderTable.button_type.intValue==5) {
            [m_button3 setHidden:NO];
            [m_button3 setBackgroundColor:MAIN_COLOR];
            m_button3.layer.borderWidth=CGFLOAT_MIN;
            [m_button3 setTitle:@"打印订单" forState:UIControlStateNormal];
            [m_button3 addTarget:self action:@selector(buttonPrintClicked:) forControlEvents:UIControlEventTouchUpInside];
            m_button3.tag=ButtonTag;
            
            [m_button1 setHidden:YES];
            [m_button2 setHidden:YES];
        }
        if (_orderTable.button_type.intValue==6) {
            [m_button3 setHidden:NO];
            [m_button3 setTitle:@"重新发单" forState:UIControlStateNormal];
            [m_button3 setTitleColor:MAIN_COLOR forState:UIControlStateNormal];
            [m_button3 setBackgroundColor:WHITE_COLOR];
            m_button3.layer.borderWidth=1.0f;
            m_button3.layer.borderColor=MAIN_COLOR.CGColor;
            [m_button3 addTarget:self action:@selector(buttonHandelClicked:) forControlEvents:UIControlEventTouchUpInside];
            m_button3.tag=ButtonTag+3;
            
            [m_button2 setHidden:NO];
            [m_button2 setTitle:@"自己配送" forState:UIControlStateNormal];
            [m_button2 addTarget:self action:@selector(buttonHandelClicked:) forControlEvents:UIControlEventTouchUpInside];
            m_button2.tag=ButtonTag+4;
            
            [m_button1 setHidden:NO];
            [m_button1 setTitle:@"打印订单" forState:UIControlStateNormal];
            [m_button1 addTarget:self action:@selector(buttonPrintClicked:) forControlEvents:UIControlEventTouchUpInside];
            m_button1.tag=ButtonTag;
        }
        if (_orderTable.button_type.intValue==7){
            [m_button3 setHidden:NO];
            [m_button3 setTitle:@"查看评价" forState:UIControlStateNormal];
            [m_button3 setTitleColor:MAIN_COLOR forState:UIControlStateNormal];
            [m_button3 setBackgroundColor:WHITE_COLOR];
            m_button3.layer.borderWidth=1.0f;
            m_button3.layer.borderColor=MAIN_COLOR.CGColor;
            [m_button3 addTarget:self action:@selector(btnCommentClicked:) forControlEvents:UIControlEventTouchUpInside];
            
            [m_button1 setHidden:YES];
            [m_button2 setHidden:YES];
        }
    }
}
-(void)addMainView
{
    m_tableView=[[UITableView alloc]init];
    m_tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    m_tableView.delegate=self;
    m_tableView.dataSource=self;
    m_tableView.showsVerticalScrollIndicator=NO;
    [self.view addSubview:m_tableView];
    [m_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(0);
        make.right.equalTo(self.view).offset(0);
        make.top.equalTo(self.view).offset(0);
        make.bottom.equalTo(self.view).offset(-60);
    }];
    [m_tableView registerNib:[UINib nibWithNibName:YCOrderStatusCellIdentify bundle:nil] forCellReuseIdentifier:YCOrderStatusCellIdentify];
    [m_tableView registerNib:[UINib nibWithNibName:YCOrderMealCellIdentify bundle:nil] forCellReuseIdentifier:YCOrderMealCellIdentify];
    [m_tableView registerNib:[UINib nibWithNibName:YCOrderAddressCellIdentify bundle:nil] forCellReuseIdentifier:YCOrderAddressCellIdentify];
    [m_tableView registerNib:[UINib nibWithNibName:YCOrderRemarkCellIdentify bundle:nil] forCellReuseIdentifier:YCOrderRemarkCellIdentify];
    [m_tableView registerNib:[UINib nibWithNibName:YCOrderDetailCellIdentify bundle:nil] forCellReuseIdentifier:YCOrderDetailCellIdentify];
    
    m_footerView=[[UIView alloc]init];
    [m_footerView setBackgroundColor:WHITE_COLOR];
    [self.view addSubview:m_footerView];
    [m_footerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(0);
        make.right.equalTo(self.view).offset(0);
        make.bottom.equalTo(self.view).offset(0);
        make.height.mas_equalTo(60);
    }];
    [m_footerView addShadowWith:CGSizeMake(kMainScreen_Width, 60)];
    [m_footerView setHidden:YES];
    
    
    CGFloat btnWidth=(kMainScreen_Width-30-20)/3;
    CGFloat btnHeight=40;
    
    m_button1=[[UIButton alloc]init];
    [m_footerView addSubview:m_button1];
    [m_button1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(m_footerView).offset(kDistance);
        make.top.equalTo(m_footerView).offset(10);
        make.width.mas_equalTo(btnWidth);
        make.height.mas_equalTo(btnHeight);
    }];
    [m_button1 setBackgroundColor:MAIN_COLOR];
    m_button1.layer.cornerRadius=2.0f;
    [m_button1.titleLabel setFont:[UIFont LightFontOfSize:16]];
    m_button1.hidden=YES;
    
    m_button2=[[UIButton alloc]init];
    [m_footerView addSubview:m_button2];
    [m_button2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(m_button1.right).offset(10);
        make.top.equalTo(m_footerView).offset(10);
        make.width.mas_equalTo(btnWidth);
        make.height.mas_equalTo(btnHeight);
    }];
    [m_button2 setBackgroundColor:MAIN_COLOR];
    m_button2.layer.cornerRadius=2.0f;
    [m_button2.titleLabel setFont:[UIFont LightFontOfSize:16]];
    m_button2.hidden=YES;
    
    m_button3=[[UIButton alloc]init];
    [m_footerView addSubview:m_button3];
    [m_button3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(m_button2.right).offset(10);
        make.top.equalTo(m_footerView).offset(10);
        make.width.mas_equalTo(btnWidth);
        make.height.mas_equalTo(btnHeight);
    }];
    [m_button3 setBackgroundColor:MAIN_COLOR];
    m_button3.layer.cornerRadius=2.0f;
    [m_button3.titleLabel setFont:[UIFont LightFontOfSize:16]];
    m_button3.hidden=YES;
}
#pragma mark tableview datasource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 5;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
#pragma mark tableview delegate
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        return 55;
    }
    if (indexPath.section==1) {
        return 150+50*_orderTable.items.count;
    }
    if (indexPath.section==2) {
        CGFloat height=getTextSize(_orderTable.addr_address, kMainScreen_Width-140, [UIFont LightFontOfSize:16]).height-18;
        return 150+height;
    }
    if (indexPath.section==3) {
        CGFloat height=0;
        if (_orderTable.remark) {
            height=getTextSize(_orderTable.remark, kMainScreen_Width-140, [UIFont LightFontOfSize:16]).height-16;
        }
        return 60+height;
    }
    return 80;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *CellIdentifier = [NSString stringWithFormat:@"cell%ld%ld",(long)indexPath.section,(long)indexPath.row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (nil == cell){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
    }
    if (indexPath.section==0) {
        YCOrderStatusTableViewCell *_cell = (YCOrderStatusTableViewCell *)[tableView dequeueReusableCellWithIdentifier:YCOrderStatusCellIdentify forIndexPath:indexPath];
        _cell.expressBlock=^(){
            YCExpressViewController *expressVC=[[YCExpressViewController alloc]init];
            expressVC.order=_orderTable;
            expressVC.cancelBlock=^(){
                [self loadData];
            };
            [self showNavigationView:expressVC];
        };
        [_cell bindWith:_orderTable];
        cell=_cell;
    }
    if (indexPath.section==1) {
        YCOrderMealTableViewCell *_cell = (YCOrderMealTableViewCell *)[tableView dequeueReusableCellWithIdentifier:YCOrderMealCellIdentify forIndexPath:indexPath];
         [_cell bindWith:_orderTable];
        cell=_cell;
    }
    if (indexPath.section==2) {
        YCOrderAddressTableViewCell *_cell = (YCOrderAddressTableViewCell *)[tableView dequeueReusableCellWithIdentifier:YCOrderAddressCellIdentify forIndexPath:indexPath];
         [_cell bindWith:_orderTable];
        cell=_cell;
    }
    if (indexPath.section==3) {
        YCOrderRemarkTableViewCell *_cell = (YCOrderRemarkTableViewCell *)[tableView dequeueReusableCellWithIdentifier:YCOrderRemarkCellIdentify forIndexPath:indexPath];
         [_cell bindWith:_orderTable];
        cell=_cell;
    }
    if (indexPath.section==4) {
        YCOrderDetailTableViewCell *_cell = (YCOrderDetailTableViewCell *)[tableView dequeueReusableCellWithIdentifier:YCOrderDetailCellIdentify forIndexPath:indexPath];
         [_cell bindWith:_orderTable];
        cell=_cell;
    }
    
    
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
-(void)buttonHandelClicked:(UIButton *)burron
{
    OrderHandelRequest *request = [OrderHandelRequest new];
    request.order_no=_orderId;
    request.type=[NSString stringWithFormat:@"%ld",burron.tag-ButtonTag];
    [apiClient doOrderHandel:request success:^(ApiResponse *data, NSString *url) {
        OrderHandelResponse *response=[[OrderHandelResponse alloc]initWithCGResponse:data];
        if (burron.tag==ButtonTag+1) {
            NSLog(@"%@",response.waiting);
        }
        //[self.view showHUD:data.message];
        [self loadData];
    }failure:^(ApiResponse *data, NSString *url){
    }];
}

-(void)buttonPrintClicked:(UIButton *)burron
{
    //[m_AlertView showAlertWith:@"用户取消订单"];
    NSUserDefaults  *userDefault = [NSUserDefaults standardUserDefaults];
    NSString *uuidString = [userDefault stringForKey:@"uuidstring"];
    if (uuidString.length==0) {
        YCConnectViewController *connectVC=[[YCConnectViewController alloc]init];
        [self showNavigationView:connectVC];
        return;
    }else{
        [self loadPrintData];
    }
    
}
-(void)loadPrintData
{
    OrderPrintRequest *request = [OrderPrintRequest new];
    [apiClient hideProgress];
    [apiClient disableAfterRequest];
    request.order_no=_orderId;
    [apiClient doOrderPrint:request success:^(ApiResponse *data, NSString *url) {
        OrderPrintResponse *response=[[OrderPrintResponse alloc]initWithCGResponse:data];
        _orderPrint=response.data;
        [self.view showHUD:@"正在打印"];
        HLPrinter *printer = [self getPrinter];
        NSData *mainData = [printer getFinalData];
        
        [[SEPrinterManager sharedInstance] sendPrintData:mainData completion:^(CBPeripheral *connectPerpheral, BOOL completion, NSString *error) {
            NSLog(@"写入数据返回结果啦");
        }];
    }failure:^(ApiResponse *data, NSString *url){
    }];
}

- (HLPrinter *)getPrinter
{
    HLPrinter *printer = [[HLPrinter alloc] init];
    
    NSString *title=[NSString stringWithFormat:@"- - - - -#%@两岸御厨订单- - - - -",_orderPrint.num];
    [printer appendText:title alignment:HLTextAlignmentCenter];
    
    [printer appendNewLine];
    [printer appendText:_orderPrint.shop_name alignment:HLTextAlignmentCenter];
    [printer appendNewLine];
    [printer appendSeperatorLine];
    
    NSString *orderType=[NSString stringWithFormat:@"%@订单",_orderPrint.express_type];
    [printer appendText:orderType alignment:HLTextAlignmentLeft fontSize:HLFontSizeTitleMiddle];
    
    NSString *orderTime=[NSString stringWithFormat:@"下单时间：%@",_orderPrint.created_at];
    [printer appendText:orderTime alignment:HLTextAlignmentLeft];
    
    NSString *sendTime=[NSString stringWithFormat:@"%@：%@",_orderPrint.meal_time_text,_orderPrint.meal_time];
    [printer appendText:sendTime alignment:HLTextAlignmentLeft];
    [printer appendSeperatorLine];
    [printer appendNewLine];
    [printer appendLeftText:@"菜名" middleText:@"数量" rightText:@"小计" isTitle:NO];
    [printer appendNewLine];
    [printer appendSeperatorLine];
    [printer appendNewLine];
    
    for (ItemTable *item in _orderPrint.items) {
        [printer appendLeftText:item.name middleText:item.num rightText:item.total_price isTitle:NO];
        [printer appendNewLine];
    }
    [printer appendSeperatorLine];
    [printer appendLeftText:@"配送费" middleText:@"" rightText:_orderPrint.express isTitle:NO];
    [printer appendSeperatorLine];
    if (_orderPrint.activity_price.intValue!=0) {
        [printer appendNewLine];
        [printer appendLeftText:_orderPrint.activity_name middleText:@"" rightText:_orderPrint.activity_price isTitle:NO];
    }
    [printer appendNewLine];
    [printer appendLeftText:_orderPrint.coupon_name middleText:@"" rightText:_orderPrint.coupon_price isTitle:NO];
    [printer appendNewLine];    
    
    [printer appendNewLine];
    NSString *money=[NSString stringWithFormat:@"(已付款)%@",_orderPrint.htotal];
    [printer appendLeftText:@"合计" rightText:money];
    [printer appendSeperatorLine];
    
    [printer appendNewLine];
    NSString *name=[NSString stringWithFormat:@"%@ %@",_orderPrint.addr_name,_orderPrint.addr_tele];
    [printer appendText:name alignment:HLTextAlignmentLeft fontSize:HLFontSizeTitleMiddle];
    [printer appendText:_orderPrint.addr_address alignment:HLTextAlignmentLeft fontSize:HLFontSizeTitleMiddle];
    
    NSString *remark=[NSString stringWithFormat:@"客户备注:%@",_orderPrint.remark];
    [printer appendText:remark alignment:HLTextAlignmentLeft];
    [printer appendText:@"\n" alignment:HLTextAlignmentLeft];
    [printer appendText:title alignment:HLTextAlignmentCenter];
    [printer appendText:@"\n\n" alignment:HLTextAlignmentLeft];
    
    [printer cutPaper];
    return printer;
}
-(void)btnCommentClicked:(UIButton *)button
{
    YCCommentsViewController *commentVC=[[YCCommentsViewController alloc]init];
    [self showNavigationView:commentVC];
}


@end
